package com.ruoyi.kindergarten.config;

import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

@Configuration
public class MqttConfig {
    // 从application.yml注入配置
    @Value("${mqtt.broker}")
    private String mqttBroker;

    @Value("${mqtt.client-id}")
    private String mqttClientId;

    @Value("${mqtt.username:}") // 冒号后是默认值（空字符串），无认证则不生效
    private String mqttUsername;

    @Value("${mqtt.password:}")
    private String mqttPassword;

    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        MqttConnectOptions options = new MqttConnectOptions();
        String[] servers = new String[]{mqttBroker};
        options.setServerURIs(servers);
        options.setKeepAliveInterval(60);
        options.setCleanSession(true);
        factory.setConnectionOptions(options);
        return factory;
    }
    @Bean(name="mqttPublishChannel")
    public MessageChannel mqttPublishChannel() {
        return new DirectChannel();
    }

//    @Bean
//    public MqttPahoMessageDrivenChannelAdapter mqttPahoMessageDrivenChannelAdapter(MqttPahoClientFactory factory) {
//        MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(
//                "1a6sd", factory, "/data" + ":" + 1);
//        adapter.setConverter(new DefaultPahoMessageConverter());
//        adapter.setOutputChannel(mqttPublishChannel());
//        return adapter;
//    }

    @Bean
    @ServiceActivator(inputChannel = "mqttPublishChannel")
    public MessageHandler mqttPublishHandler(MqttPahoClientFactory factory) {
        MqttPahoMessageHandler handler = new MqttPahoMessageHandler("1a6sd", factory);
        handler.setAsync(true);
        handler.setDefaultQos(1);
        return handler;
    }
}
